package com.kc.road.camera.service;

import com.kc.road.camera.common.Constants;
import com.kc.road.camera.util.JacksonUtil;
import com.kc.road.camera.vo.CameraVo;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeoutException;

/**
 * Created by yzm on 2018/3/1.
 */
@Service
public class RabbitMessageSenderService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private AmqpTemplate rabbitTemplate;

    /**
     * 发送消息
     */
    public void sender(String cameraExchange, String routingKey, CameraVo vo) {
        //发送rabbitmq消息
        try {
            rabbitTemplate.convertAndSend(cameraExchange,routingKey,JacksonUtil.toJSon(vo).getBytes(Constants.CHARSET_UTF8));
            logger.info("amqpTemplate发送消息");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static void sendMessage(String cameraExchange, String routingKey, CameraVo vo) {
        //发送rabbitmq消息
        String value = JacksonUtil.toJSon(vo);
        System.out.println("cameraExchange==" + cameraExchange);
        System.out.println("routingKey==" + routingKey);
        System.out.println("value==" + value);
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(ConnectionFactory.DEFAULT_HOST);
        factory.setPort(ConnectionFactory.DEFAULT_AMQP_PORT);
        factory.setUsername("road1");
        factory.setPassword("111111");
        factory.setVirtualHost("road_vir1");
        try {
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();
            channel.basicPublish(cameraExchange, routingKey, MessageProperties.BASIC, value.getBytes(Constants.CHARSET_UTF8));
            channel.close();
            connection.close();
            factory.clone();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }

}
